package com.yyw.foodie.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyw.foodie.enums.OrderEnums;
import com.yyw.foodie.enums.YesOrNoEnums;
import com.yyw.foodie.exceptions.OrderStatusException;
import com.yyw.foodie.pojo.OrderStatusEntity;
import com.yyw.foodie.pojo.OrdersEntity;
import com.yyw.foodie.service.OrderStatusService;
import com.yyw.foodie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 易煜玮
 * @ClassName BaseController.java
 * @Description 控制器基类
 * @createTime 2021年06月04日 15:45:00
 */
@Component
public class BaseController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderStatusService orderStatusService;

    /**
     * 检查传入用户是否传入订单的所有者，判断能否操作订单
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return
     */
    public OrdersEntity checkUserIsOperatingByComments(String userId, String orderId) {
        QueryWrapper<OrdersEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrdersEntity::getUserId, userId)
                .eq(OrdersEntity::getId, orderId)
                .eq(OrdersEntity::getIsDelete, YesOrNoEnums.否.code);
        OrdersEntity entity = ordersService.getOne(queryWrapper);
        if (entity == null) {
            throw new OrderStatusException("该用户没有权限操作订单或订单不存在");
        }
        // 检验是否可操作
        if (YesOrNoEnums.是.code.equals(entity.getIsComment())) {
            throw new OrderStatusException("该订单已评价，不能再次评价！");
        }
        OrderStatusEntity statusEntity = orderStatusService.getById(orderId);
        if (!OrderEnums.交易成功.code.equals(statusEntity.getOrderStatus())) {
            throw new OrderStatusException("该订单现状态无法评价，请确认收货后再进行评价操作！");
        }
        return entity;
    }

}
